<template>
  <div class="training-management-container">
    <div class="page-header">
      <h2>培训管理</h2>
      <p>管理党员培训课程与活动</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-blue">
              <el-icon>
                <School />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalCount }}</div>
              <div class="stat-label">培训课程总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-green">
              <el-icon>
                <User />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.participantCount }}</div>
              <div class="stat-label">参训人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-orange">
              <el-icon>
                <Calendar />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.ongoingCount }}</div>
              <div class="stat-label">进行中培训</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-purple">
              <el-icon>
                <PieChart />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.completionRate }}%</div>
              <div class="stat-label">平均完成率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="培训名称">
            <el-input v-model="searchForm.name" placeholder="请输入培训名称" clearable @clear="handleInputClear('name')"
              @input="debounceSearch" />
          </el-form-item>
          <el-form-item label="培训类型">
            <el-select v-model="searchForm.type" placeholder="请选择培训类型" clearable @change="handleTypeChange">
              <el-option label="理论学习" value="theory" />
              <el-option label="专题培训" value="special" />
              <el-option label="党务培训" value="party_affairs" />
              <el-option label="技能培训" value="skills" />
              <el-option label="读书交流" value="book_club" />
            </el-select>
          </el-form-item>
          <el-form-item label="培训状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable @change="handleStatusChange">
              <el-option label="未开始" value="pending" />
              <el-option label="进行中" value="ongoing" />
              <el-option label="已结束" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTrainings">
              <el-icon>
                <Search />
              </el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon>
                <Refresh />
              </el-icon> 重置
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon>
                <Plus />
              </el-icon> 新增培训
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 培训列表表格 -->
    <el-card class="table-card" shadow="hover" v-loading="loading">
      <el-table :data="trainingList" border style="width: 100%" row-key="id">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="培训名称" min-width="120" />
        <el-table-column prop="type" label="培训类型" min-width="100">
          <template #default="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="start_date" label="开始日期" min-width="100" />
        <el-table-column prop="end_date" label="结束日期" min-width="100" />
        <el-table-column prop="location" label="培训地点" min-width="120" />
        <el-table-column prop="trainer" label="培训讲师" min-width="100" />
        <el-table-column prop="participant_count" label="参训人数" width="100" align="center" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" plain @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon> 查看
              </el-button>
              <el-button size="small" type="warning" plain @click="handleEdit(scope.row)">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <!-- <el-button size="small" type="success" plain @click="handleManageParticipants(scope.row)" v-if="scope.row.status !== 'cancelled'">
                <el-icon><UserFilled /></el-icon> 管理学员
              </el-button> -->
              <el-button size="small" type="danger" plain @click="handleDelete(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看培训详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="培训详情" width="800px" :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="培训名称">{{ currentTraining.name }}</el-descriptions-item>
        <el-descriptions-item label="培训类型">{{ getTypeText(currentTraining.type) }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ currentTraining.start_date }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">{{ currentTraining.end_date }}</el-descriptions-item>
        <el-descriptions-item label="培训地点">{{ currentTraining.location }}</el-descriptions-item>
        <el-descriptions-item label="培训讲师">{{ currentTraining.trainer }}</el-descriptions-item>
        <el-descriptions-item label="培训状态">
          <el-tag :type="getStatusTagType(currentTraining.status)">{{ getStatusText(currentTraining.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="参训人数">{{ currentTraining.participant_count }}人</el-descriptions-item>
        <el-descriptions-item label="培训内容" :span="2">
          <div class="training-content">
            {{ currentTraining.content || '暂无内容' }}
          </div>
        </el-descriptions-item>
        <!-- <el-descriptions-item label="培训材料" :span="2">
          <div class="training-materials">
            <div v-if="currentTraining.materials && currentTraining.materials.length">
              <div v-for="(material, index) in currentTraining.materials" :key="index" class="material-item">
                <el-tag size="small" type="info">{{ getMaterialTypeText(material.type) }}</el-tag>
                <span class="material-name">{{ material.name }}</span>
                <el-button type="primary" link size="small">下载</el-button>
              </div>
            </div>
            <span v-else>暂无培训材料</span>
          </div>
        </el-descriptions-item> -->
        <el-descriptions-item label="备注" :span="2">
          <div class="training-remarks">
            {{ currentTraining.remarks || '无' }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑培训对话框 -->
    <el-dialog v-model="editDialogVisible" :title="isEdit ? '编辑培训' : '新增培训'" width="800px"
      :close-on-click-modal="false">
      <el-form :model="trainingForm" :rules="trainingFormRules" ref="trainingFormRef" label-width="100px">
        <el-form-item label="培训名称" prop="name">
          <el-input v-model="trainingForm.name" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="培训类型" prop="type">
          <el-select v-model="trainingForm.type" placeholder="请选择培训类型">
            <el-option label="理论学习" value="theory" />
            <el-option label="专题培训" value="special" />
            <el-option label="党务培训" value="party_affairs" />
            <el-option label="技能培训" value="skills" />
            <el-option label="读书交流" value="book_club" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训时间" prop="dateRange">
          <el-date-picker v-model="trainingForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="培训地点" prop="location">
          <el-input v-model="trainingForm.location" placeholder="请输入培训地点" />
        </el-form-item>
        <el-form-item label="培训讲师" prop="trainer">
          <el-input v-model="trainingForm.trainer" placeholder="请输入培训讲师姓名" />
        </el-form-item>
        <el-form-item label="培训状态" prop="status">
          <el-select v-model="trainingForm.status" placeholder="请选择培训状态">
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训内容" prop="content">
          <el-input v-model="trainingForm.content" type="textarea" :rows="5" placeholder="请输入培训内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="trainingForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTraining" :loading="submitting">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 管理学员对话框 -->
    <el-dialog v-model="participantsDialogVisible" title="管理培训学员" width="900px" :close-on-click-modal="false">
      <div class="participant-management">
        <div class="participant-search">
          <el-input v-model="participantSearchKeyword" placeholder="搜索学员姓名" clearable :prefix-icon="Search"
            @input="searchParticipants" />
          <el-button type="primary" @click="handleAddParticipants">
            <el-icon>
              <Plus />
            </el-icon> 添加学员
          </el-button>
        </div>

        <el-table :data="participantList" border style="width: 100%" v-loading="participantsLoading">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="department" label="所属部门" min-width="120" />
          <el-table-column prop="position" label="职务" min-width="100" />
          <el-table-column prop="attendance" label="出勤情况" min-width="100">
            <template #default="scope">
              <el-select v-model="scope.row.attendance" placeholder="选择出勤情况"
                @change="handleAttendanceChange(scope.row)">
                <el-option label="全勤" value="full" />
                <el-option label="请假" value="leave" />
                <el-option label="缺席" value="absent" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="completion" label="完成度" min-width="100">
            <template #default="scope">
              <el-progress :percentage="scope.row.completion" />
            </template>
          </el-table-column>
          <el-table-column prop="score" label="考核成绩" min-width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.score" :min="0" :max="100" @change="handleScoreChange(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" plain @click="handleRemoveParticipant(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon> 移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="participantsDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="saveParticipants">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加学员对话框 -->
    <el-dialog v-model="addParticipantsDialogVisible" title="添加培训学员" width="800px" append-to-body
      :close-on-click-modal="false">
      <div class="add-participants">
        <el-input v-model="addParticipantKeyword" placeholder="搜索学员姓名或部门" clearable :prefix-icon="Search"
          style="margin-bottom: 15px" />

        <el-table :data="availableParticipants" border style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="department" label="所属部门" min-width="120" />
          <el-table-column prop="position" label="职务" min-width="100" />
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addParticipantsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddParticipants">确认添加</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, View, Edit, Delete, Plus, School,
  User, UserFilled, Calendar, PieChart, Setting
} from '@element-plus/icons-vue';

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const trainingList = ref([]);

// 统计数据
const statsData = reactive({
  totalCount: 0,
  participantCount: 0,
  ongoingCount: 0,
  completionRate: 0
});

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
});

// 详情对话框
const viewDialogVisible = ref(false);
const currentTraining = ref({});

// 编辑对话框
const editDialogVisible = ref(false);
const isEdit = ref(false);
const trainingFormRef = ref(null);
const submitting = ref(false);
const trainingForm = reactive({
  id: '',
  name: '',
  type: '',
  dateRange: [],
  start_date: '',
  end_date: '',
  location: '',
  trainer: '',
  status: 'pending',
  content: '',
  remarks: '',
  participant_count: 0,
  materials: []
});

// 表单校验规则
const trainingFormRules = {
  name: [{ required: true, message: '请输入培训名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
  dateRange: [{ required: true, message: '请选择培训时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入培训地点', trigger: 'blur' }],
  trainer: [{ required: true, message: '请输入培训讲师', trigger: 'blur' }],
  status: [{ required: true, message: '请选择培训状态', trigger: 'change' }],
  content: [{ required: true, message: '请输入培训内容', trigger: 'blur' }]
};

// 学员管理相关
const participantsDialogVisible = ref(false);
const participantSearchKeyword = ref('');
const participantsLoading = ref(false);
const participantList = ref([]);
const addParticipantsDialogVisible = ref(false);
const addParticipantKeyword = ref('');
const selectedParticipants = ref([]);
const availableParticipants = ref([]);

// 初始化加载数据
onMounted(() => {
  fetchTrainings();
});

// 获取培训列表
const fetchTrainings = async () => {
  loading.value = true;
  try {
    // 这里应调用后端API获取数据
    // 模拟API响应
    setTimeout(() => {
      trainingList.value = [
        {
          id: '1',
          name: '党的二十大精神学习培训',
          type: 'theory',
          start_date: '2023-03-15',
          end_date: '2023-03-20',
          location: '党员活动中心',
          trainer: '王教授',
          participant_count: 30,
          status: 'completed',
          content: '学习贯彻党的二十大精神，深入理解习近平新时代中国特色社会主义思想，增强"四个意识"，坚定"四个自信"，做到"两个维护"。',
          remarks: '全体党员必须参加',
          materials: [
            { type: 'document', name: '党的二十大报告学习资料.pdf' },
            { type: 'video', name: '党的二十大开幕式视频.mp4' }
          ]
        },
        {
          id: '2',
          name: '党务工作培训班',
          type: 'party_affairs',
          start_date: '2023-04-10',
          end_date: '2023-04-15',
          location: '市委党校',
          trainer: '李书记',
          participant_count: 25,
          status: 'completed',
          content: '培训内容包括党支部工作规范、党员发展流程、党内政治生活组织等党务实操知识。',
          remarks: '支部书记、组织委员参加',
          materials: [
            { type: 'document', name: '党支部工作手册.pdf' },
            { type: 'document', name: '党员发展工作流程.docx' }
          ]
        },
        {
          id: '3',
          name: '党史学习教育专题培训',
          type: 'special',
          start_date: '2023-05-18',
          end_date: '2023-05-19',
          location: '线上会议室',
          trainer: '张教授',
          participant_count: 50,
          status: 'completed',
          content: '开展党史学习教育，了解党的光辉历程，汲取奋进力量。',
          remarks: '采用线上培训方式，全体党员参加',
          materials: [
            { type: 'document', name: '中国共产党简史.pdf' },
            { type: 'ppt', name: '党史重要事件解读.pptx' }
          ]
        },
        {
          id: '4',
          name: '青年党员骨干培训班',
          type: 'skills',
          start_date: '2023-06-20',
          end_date: '2023-06-25',
          location: '党员培训中心',
          trainer: '赵主任',
          participant_count: 20,
          status: 'ongoing',
          content: '培养青年党员骨干，提升政治素养和领导能力，内容包括理论学习、实践锻炼、经验交流等环节。',
          remarks: '35岁以下党员代表参加',
          materials: [
            { type: 'document', name: '青年党员成长指南.pdf' }
          ]
        },
        {
          id: '5',
          name: '党建工作创新研讨会',
          type: 'special',
          start_date: '2023-07-15',
          end_date: '2023-07-15',
          location: '会议中心三楼',
          trainer: '钱教授',
          participant_count: 40,
          status: 'pending',
          content: '探讨新形势下党建工作创新思路，交流基层党建工作经验，推广先进做法。',
          remarks: '各支部至少派一名代表参加',
          materials: []
        },
        {
          id: '6',
          name: '"四史"读书交流会',
          type: 'book_club',
          start_date: '2023-08-05',
          end_date: '2023-08-05',
          location: '图书馆会议室',
          trainer: '孙老师',
          participant_count: 35,
          status: 'pending',
          content: '围绕党史、新中国史、改革开放史、社会主义发展史开展读书交流活动，分享学习心得。',
          remarks: '需提前准备读书笔记',
          materials: []
        }
      ];
      total.value = 6;

      // 更新统计数据
      updateStatsData();

      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('获取培训列表失败:', error);
    ElMessage.error('获取培训列表失败，请稍后重试');
    loading.value = false;
  }
};

// 更新统计数据
const updateStatsData = () => {
  // 计算总数
  statsData.totalCount = trainingList.value.length;

  // 计算参训人数总数
  let totalParticipants = 0;
  trainingList.value.forEach(item => {
    totalParticipants += item.participant_count;
  });
  statsData.participantCount = totalParticipants;

  // 计算进行中培训数量
  statsData.ongoingCount = trainingList.value.filter(item => item.status === 'ongoing').length;

  // 计算平均完成率 (模拟数据)
  statsData.completionRate = 85;
};

// 搜索培训
const searchTrainings = () => {
  currentPage.value = 1;
  fetchTrainings();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
  fetchTrainings();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTrainings();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTrainings();
};

// 处理输入框清除
const handleInputClear = (key) => {
  searchForm[key] = '';
  fetchTrainings();
};

// 处理类型变化
const handleTypeChange = () => {
  fetchTrainings();
};

// 处理状态变化
const handleStatusChange = () => {
  fetchTrainings();
};

// 获取培训类型文本
const getTypeText = (type) => {
  const types = {
    theory: '理论学习',
    special: '专题培训',
    party_affairs: '党务培训',
    skills: '技能培训',
    book_club: '读书交流'
  };
  return types[type] || type;
};

// 获取状态文本
const getStatusText = (status) => {
  const statuses = {
    pending: '未开始',
    ongoing: '进行中',
    completed: '已结束',
    cancelled: '已取消'
  };
  return statuses[status] || status;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    pending: 'info',
    ongoing: 'success',
    completed: '',
    cancelled: 'danger'
  };
  return types[status] || '';
};

// 获取材料类型文本
const getMaterialTypeText = (type) => {
  const types = {
    document: '文档',
    video: '视频',
    ppt: '幻灯片',
    audio: '音频',
    other: '其他'
  };
  return types[type] || '未知';
};

// 查看培训详情
const handleView = (row) => {
  currentTraining.value = { ...row };
  viewDialogVisible.value = true;
};

// 新增培训
const handleAdd = () => {
  isEdit.value = false;
  Object.keys(trainingForm).forEach(key => {
    if (key === 'status') {
      trainingForm[key] = 'pending';
    } else if (key === 'dateRange') {
      trainingForm[key] = [];
    } else if (key === 'participant_count') {
      trainingForm[key] = 0;
    } else if (key === 'materials') {
      trainingForm[key] = [];
    } else {
      trainingForm[key] = '';
    }
  });
  editDialogVisible.value = true;
};

// 编辑培训
const handleEdit = (row) => {
  isEdit.value = true;
  Object.keys(trainingForm).forEach(key => {
    if (key === 'dateRange') {
      trainingForm[key] = [row.start_date, row.end_date];
    } else {
      trainingForm[key] = row[key];
    }
  });
  editDialogVisible.value = true;
};

// 删除培训
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除"${row.name}"培训吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 执行删除操作
    // 这里应调用后端API删除数据
    const index = trainingList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      trainingList.value.splice(index, 1);
      total.value -= 1;

      // 更新统计数据
      updateStatsData();
    }
    ElMessage.success(`删除"${row.name}"培训成功`);
  }).catch(() => { });
};

// 管理培训学员
const handleManageParticipants = (row) => {
  // 加载该培训的学员列表
  participantsLoading.value = true;
  currentTraining.value = { ...row };

  // 模拟API请求加载学员数据
  setTimeout(() => {
    participantList.value = [
      {
        id: '1',
        name: '张三',
        department: '技术部',
        position: '工程师',
        attendance: 'full',
        completion: 100,
        score: 95
      },
      {
        id: '2',
        name: '李四',
        department: '人事部',
        position: '主管',
        attendance: 'full',
        completion: 90,
        score: 88
      },
      {
        id: '3',
        name: '王五',
        department: '财务部',
        position: '会计',
        attendance: 'leave',
        completion: 70,
        score: 75
      },
      {
        id: '4',
        name: '赵六',
        department: '市场部',
        position: '经理',
        attendance: 'full',
        completion: 95,
        score: 90
      },
      {
        id: '5',
        name: '钱七',
        department: '行政部',
        position: '文员',
        attendance: 'absent',
        completion: 40,
        score: 60
      }
    ];
    participantsLoading.value = false;
    participantsDialogVisible.value = true;
  }, 500);
};

// 搜索学员
const searchParticipants = () => {
  // 根据关键词搜索学员
  // 实际项目中应调用API进行搜索
  console.log('搜索学员:', participantSearchKeyword.value);
};

// 添加学员对话框
const handleAddParticipants = () => {
  // 加载可添加的学员列表
  // 模拟API请求
  setTimeout(() => {
    availableParticipants.value = [
      {
        id: '6',
        name: '孙八',
        department: '技术部',
        position: '程序员'
      },
      {
        id: '7',
        name: '周九',
        department: '人事部',
        position: '招聘专员'
      },
      {
        id: '8',
        name: '吴十',
        department: '市场部',
        position: '销售代表'
      },
      {
        id: '9',
        name: '郑十一',
        department: '财务部',
        position: '出纳'
      },
      {
        id: '10',
        name: '王十二',
        department: '行政部',
        position: '前台'
      }
    ];
    addParticipantsDialogVisible.value = true;
  }, 300);
};

// 处理学员选择变化
const handleSelectionChange = (selection) => {
  selectedParticipants.value = selection;
};

// 确认添加学员
const confirmAddParticipants = () => {
  if (selectedParticipants.value.length === 0) {
    ElMessage.warning('请选择要添加的学员');
    return;
  }

  // 将选中的学员添加到参与者列表
  selectedParticipants.value.forEach(participant => {
    participantList.value.push({
      ...participant,
      attendance: 'full',
      completion: 0,
      score: 0
    });
  });

  // 更新参训人数
  currentTraining.value.participant_count = participantList.value.length;

  // 更新培训列表中的数据
  const index = trainingList.value.findIndex(item => item.id === currentTraining.value.id);
  if (index !== -1) {
    trainingList.value[index].participant_count = participantList.value.length;
  }

  ElMessage.success(`成功添加${selectedParticipants.value.length}名学员`);
  addParticipantsDialogVisible.value = false;
};

// 移除学员
const handleRemoveParticipant = (row) => {
  ElMessageBox.confirm(
    `确定要移除学员"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = participantList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      participantList.value.splice(index, 1);

      // 更新参训人数
      currentTraining.value.participant_count = participantList.value.length;

      // 更新培训列表中的数据
      const trainingIndex = trainingList.value.findIndex(item => item.id === currentTraining.value.id);
      if (trainingIndex !== -1) {
        trainingList.value[trainingIndex].participant_count = participantList.value.length;
      }
    }
    ElMessage.success(`成功移除学员"${row.name}"`);
  }).catch(() => { });
};

// 处理考勤变化
const handleAttendanceChange = (row) => {
  console.log('考勤变化:', row.name, row.attendance);
};

// 处理成绩变化
const handleScoreChange = (row) => {
  console.log('成绩变化:', row.name, row.score);
};

// 保存学员管理
const saveParticipants = () => {
  // 保存学员信息
  // 实际项目中应调用API保存数据
  ElMessage.success('学员信息保存成功');
  participantsDialogVisible.value = false;
};

// 提交培训表单
const submitTraining = async () => {
  if (!trainingFormRef.value) return;

  trainingFormRef.value.validate(async (valid) => {
    if (!valid) return;

    submitting.value = true;
    try {
      // 处理日期范围
      if (trainingForm.dateRange && trainingForm.dateRange.length === 2) {
        trainingForm.start_date = trainingForm.dateRange[0];
        trainingForm.end_date = trainingForm.dateRange[1];
      }

      // 这里应调用后端API提交数据
      // 模拟API调用
      setTimeout(() => {
        if (isEdit.value) {
          // 更新现有记录
          const index = trainingList.value.findIndex(item => item.id === trainingForm.id);
          if (index !== -1) {
            trainingList.value[index] = { ...trainingForm };
          }
          ElMessage.success('更新培训成功');
        } else {
          // 添加新记录
          const newId = Date.now().toString();
          trainingList.value.unshift({
            ...trainingForm,
            id: newId,
            participant_count: 0,
            materials: []
          });
          total.value += 1;
          ElMessage.success('添加培训成功');
        }

        // 更新统计数据
        updateStatsData();

        editDialogVisible.value = false;
        submitting.value = false;
      }, 500);
    } catch (error) {
      console.error('提交培训失败:', error);
      ElMessage.error('提交培训失败，请稍后重试');
      submitting.value = false;
    }
  });
};

// 即时搜索
const debounceSearch = () => {
  fetchTrainings();
};
</script>

<style scoped>
.training-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100px;
  padding: 0 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 28px;
  color: white;
}

.bg-blue {
  background-color: #409EFF;
}

.bg-green {
  background-color: #67C23A;
}

.bg-orange {
  background-color: #E6A23C;
}

.bg-purple {
  background-color: #909399;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.training-content,
.training-remarks {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.training-materials {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.material-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.material-name {
  margin: 0 10px;
  flex: 1;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
  width: 100%;
}

.participant-management {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.participant-search {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.participant-search .el-input {
  width: 300px;
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }

  .participant-search {
    flex-direction: column;
    gap: 10px;
  }

  .participant-search .el-input {
    width: 100%;
  }
}
</style>